package servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Random;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import po.Cart;
import service.CartService;
import service.impl.CartServiceImpl;

/**
 * Servlet implementation class AddCartServlet
 */
public class AddCartServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public AddCartServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setCharacterEncoding("UTF-8");
    	response.setHeader("content-type","text/html;charset=UTF-8");
    	PrintWriter printWriter = response.getWriter();
		int dId = Integer.parseInt(request.getParameter("dId"));
		int cId = Integer.parseInt(request.getParameter("cId"));
		String cartId = System.currentTimeMillis() + "" + new Random().nextInt(10) + "" + new Random().nextInt(10) + "" + new Random().nextInt(10);
		String cdId = System.currentTimeMillis() + "" + new Random().nextInt(10) + "" + new Random().nextInt(10) + "" + new Random().nextInt(10);
		CartService cartServiceImpl = new CartServiceImpl();
		int dNum = 1;
		Cart cart = new Cart(cartId, dNum, cdId, dId);
		int m = cartServiceImpl.addCart(cart , cId);
		if(m>0){
			printWriter.print("添加成功");
			request.getRequestDispatcher("ShowCartServlet").forward(request, response);
		}else{
			printWriter.print("添加失败");
			response.sendRedirect("index.jsp");
		}
		
	}

}
